<?php
namespace app\client\controller;
use app\common\lib\Redis;
use think\swoole\facade\Task;

class Chat extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function chat() {
    	$id = request()->get('id', 0, 'intval');
        if($id <= 0){
            return errorResult('abc' . $id);
        }
        
        $redis = new Redis();
        
        try {
        	$chat = $redis->get('chat_' . $id);
        	
        	if(empty($chat)){
        		$chat = model('Chat')->findOne(['chat_id' => $id], ['content', 'chat_type', 'picture', 'user_id', 'location', 'longitude', 'latitude', 'create_time']);
        		if(empty($chat)){
        			return errorResult('记录已被删除', 404);
        		}
        		$chat['picture'] = json_decode($chat['picture'], true);
        		
        	}else{
        		$chat = json_decode($chat, true);
        	}
        	
        	if($chat['chat_type'] == 2 || $chat['chat_type'] == 5) { //商品
        	    //查看是否是代理商
        	    $chat['isAgent'] = model('Agent')->isAgent($this->userid, $chat['user_id']);
        	    
        	    if($chat['chat_type'] == 5) { //查看是否已经砍价
        	        $rs = model('UserBargain')->findOne(['user_id' => $this->userid, 'chat_id' => $id], ['status', 'id', 'expire_time']);
        	        if(!empty($rs) && $rs['status'] == 0 && $rs['expire_time'] > time()) {
        	            $chat['bargain'] = 1;
        	            $chat['bargain_id'] = $rs['id'];
        	        }
        	    }
        	}
        	
        	

        	
        	//查看是否收藏了
        	$collectId = model('ChatCollect')->where(['user_id' => $this->userid, 'chat_id' => $id])->value('id');
        	$chat['collectStatus'] = $collectId === null ? false : true;
        	
        	//查看是否点赞了
        	$parisetId = model('ChatPraise')->where(['user_id' => $this->userid, 'chat_id' => $id])->value('id');
        	$chat['praiseStatus'] = $parisetId === null ? false : true;
        	
        	$chat['user'] = $redis->get('user_' . $chat['user_id']);
        	
        	$redis->close();
        	
        	return successResult($chat);
        } catch (\Exception $e) {
        	$redis->close();
        	return errorResult();
        }
    }
    
    //收藏说说
    public function collect(){
    	$id = request()->get('id', 0, 'intval');
    	if($id <= 0){
    		return errorResult();
    	}
    	$model = model('ChatCollect');
    	$chat = $model->findOne(['user_id' => $this->userid, 'chat_id' => $id], ['id']);
    	if(!empty($chat)){
    		return errorResult('已经收藏了');
    	}
    	
    	$id = $model->add(['user_id' => $this->userid, 'chat_id' => $id, 'add_time' => time()]);
    	
    	if(!$id){
    		return errorResult();
    	}
    	
    	return successResult(['id' => $id]);
    }
    
    //取消收藏说说
    public function uncollect(){
    	$chatId = request()->get('id', 0, 'intval');
    	if($chatId <= 0){
    		return errorResult();
    	}
    	$model = model('ChatCollect');
    	$chat = $model->findOne(['user_id' => $this->userid, 'chat_id' => $chatId], ['id']);
    	if(empty($chat)){
    		return errorResult();
    	}
    	
    	if($model->where(['id' => $chat['id']])->delete()){
    		return successResult('取消收藏成功');
    	}else{
    		return errorResult();
    	}
    }
    
    //点赞
    public function praise(){
    	$chatId = request()->get('id', 0, 'intval');
    	if($chatId <= 0){
    		return errorResult();
    	}
    	$model = model('ChatPraise');
    	$chat = $model->findOne(['user_id' => $this->userid, 'chat_id' => $chatId], ['id']);
    	if(!empty($chat)){
    		return errorResult('已经点赞了');
    	}
    	 
    	$id = $model->add(['user_id' => $this->userid, 'chat_id' => $chatId, 'create_time' => time()]);
    	 
    	if(!$id){
    		return errorResult();
    	}
    	
    	Task::async(function () use($chatId){
    		$redis = new Redis();
    		try {
    		    $chat = $redis->get('chat_' . $chatId);
    		    if(!empty($chat)) {
    		        $chat = json_decode($chat, true);
    		        $userId = $chat['user_id'];
    		        unset($chat);
    		        $redis->incrBy(redisUserChatPraiseKey($userId), 1);
    		    }
    		} catch (\Exception $e) {
    		}
    		
    		try {
    		    $redis->incrBy(redisChatPraisekey($chatId), 1);
    		} catch (\Exception $e) {
    		}
    		
    		$redis->close();
    		
    		return true;
    	});
    	
    	return successResult();
    }
    
    //取消点赞
    public function unpraise(){
    	$chatId = request()->get('id', 0, 'intval');
    	if($chatId <= 0){
    		return errorResult();
    	}
    	
    	$userId = $this->userid;
    	
    	$model = model('ChatPraise');
    	$chat = $model->findOne(['chat_id' => $chatId, 'user_id' => $userId], ['id']);
    	if(empty($chat)){
    		return errorResult();
    	}
    	 
    	if($model->where(['id' => $chat['id']])->delete()){
    	    Task::async(function () use($chatId){
    	        $redis = new Redis();
    	        try {
    	            $chat = $redis->get('chat_' . $chatId);
    	            if(!empty($chat)) {
    	                $chat = json_decode($chat, true);
    	                $userId = $chat['user_id'];
    	                unset($chat);
    	                $redis->incrBy(redisUserChatPraiseKey($userId), -1);
    	            }
    	        } catch (\Exception $e) {
    	        }
    	        
    	        try {
    	            $redis->incrBy(redisChatPraisekey($chatId), -1);
    	        } catch (\Exception $e) {
    	        }
    	        
    	        $redis->close();
    	        
    	        return true;
    	    });
    		
    		return successResult('取消点赞成功');
    	}else{
    		return errorResult();
    	}
    }
    
    //动态
    public function dynamics() {
    	$params = request()->get();
    	$pk = isset($params['lastPk']) ? intval($params['lastPk']) : 0;
    	$last = isset($params['last']) ? intval($params['last']) : 0;
    	
    	$userIds = model('FollowUser')->values(['follow_user_id' => $this->userid], 'user_id');
    	array_push($userIds, $this->userid);
    	
    	
    	$where = [['user_id', 'in', $userIds], ['chat_type', 'in', [1, 2, 4, 5]]];
    	if($pk > 0) {
    	    if($last == 0) {
    	        $where[] = ['chat_id', '<', $pk];
    	    }else{
    	        $where[] = ['chat_id', '>', $pk];
    	    }
    		
    	}
    	
    	
        $chatList = model('Chat')
        ->where($where)
        ->field(['chat_id', 'user_id', 'content', 'picture', 'chat_type', 'create_time', 'location', 'longitude', 'latitude'])
        ->order('chat_id desc')
        ->limit(20)
        ->select()
        ->toArray();
        
        
        
        
        if(!empty($chatList)) {
        	$userIds = [];
        	$chatIds = [];
        	$bargainChatId = [];
        	$goodsIds = [];
        	foreach ($chatList as $v) {
        	    if($v['chat_type'] != 1) { //商品类的
        	        array_push($goodsIds, $v['chat_id']);
        	    }
        	    
        		$key = 'user_' . $v['user_id'];
        		if(!in_array($key, $userIds)){
        			array_push($userIds, $key);
        		}
        		
        		array_push($chatIds, $v['chat_id']);
        		
        	}
        	if(!empty($goodsIds)) {
        	    $goodsList = model('ChatGoods')->findAll(['chat_id' => $goodsIds], ['goods_name', 'chat_id']);
        	    foreach ($chatList as $k => $chat) {
        	        foreach ($goodsList as $i => $goods) {
        	            if($chat['chat_id'] == $goods['chat_id']) {
        	                $chatList[$k]['goods_name'] = $goods['goods_name'];
        	                unset($goodsList[$i]);
        	                break;
        	            }
        	        }
        	    }
        	}
        	
        	/* if(!empty($bargainChatId)) {
        	    $time = time();
        	    $where = [
        	        ['user_id', '=', $this->userid],
        	        ['expire_time', '>', $time],
        	        ['status', '=', 0],
        	        ['chat_id', 'in', $bargainChatId]
        	    ];
        	    $rows = model('UserBargain')->findAll($where, ['chat_id', 'id']);
        	    if(!empty($rows)) {
        	        foreach ($chatList as &$v) {
        	            foreach ($rows as $k => $row) {
        	                if($row['chat_id'] == $v['chat_id']) {
        	                    $v['bargain'] = 1;
        	                    $v['bargain_id'] = $row['id'];
        	                    unset($rows[$k]);
        	                    break;
        	                }
        	            }
        	        }
        	    }
        	} */
        	
        	
        	$praiseList = [];
        	$praises = model('ChatPraise')->findAll(['chat_id' => $chatIds, 'user_id' => $this->userid], 'chat_id');
        	foreach ($praises as $praise) {
        		array_push($praiseList, $praise['chat_id']);
        	}
        	
        	$redis = new Redis();
        	$users = $redis->mget($userIds);
        	$userList = [];
        	foreach ($users as $user) {
        		$user = json_decode($user, true);
        		$userList[$user['user_id']] = $user;
        	}
        	
        	foreach ($chatList as &$chat) {
        		$chat['user'] = $userList[$chat['user_id']];
        		$chat['praise'] = in_array($chat['chat_id'], $praiseList) ? 1 : 0;
        	}
        }
        
        return successResult(['list' => $chatList]);
    }
    
    
    //领取分享的红包
    public function grabShareAmount() {
        $params = request()->post();
        $sharer = isset($params['sharer']) ? intval($params['sharer']) : 0;
        if($sharer <= 0){
            return errorResult('a');
        }
        
        $chatId = isset($params['chatId']) ? intval($params['chatId']) : 0;
        if($chatId <= 0){
            return errorResult('a');
        }
        
        $userId = $this->userid;
        
        if($sharer == $userId) {
            return errorResult('b22');
        }
        
        //查看有无领取过
        $receiveLogModel = model('GoodsRedenvelopeReceiveLog');
        $receiveLog = $receiveLogModel->findOne(['user_id' => $sharer, 'chat_id' => $chatId, 'hit_user_id' => $userId], ['amount']);
        if(!empty($receiveLog)){
            return successResult(['amount' => $receiveLog['amount']]);
        }
        
        $redis = new Redis();
        
        $amount = $redis->handler()->lPop('goods_redenvelope__list_' . $chatId); //抢到的红包金额
        
        if($amount === false){
            $redis->close();
            return successResult(['amount' => 0]);
        }
        $chat = $redis->get('chat_' . $chatId);
        $redis->close();
        
        $chat = json_decode($chat, true);
        
        $walletModel = model('UserWallet');
        
        $walletModel->startTrans();
        
        try {
            $wallet = $walletModel->where(['user_id' => $userId])->field(['amount', 'redenvelope_amount'])->lock(true)->find();
            if(empty($wallet)) {
                $walletModel->rollback();
                return errorResult('b');
            }
            
            $wallet = $wallet->toArray();
            
            $rs = $walletModel->modify(['user_id' => $userId], ['amount' => $wallet['amount'] + $amount, 'redenvelope_amount' => $wallet['redenvelope_amount'] + $amount]);
            if(!$rs) {
                $walletModel->rollback();
                return errorResult('c');
            }
            
            $redenvelopeModel = model('GoodsRedenvelope');
            
            $redenvelope = $redenvelopeModel->where(['chat_id' => $chatId])->field(['id', 'quantity', 'receive_quantity', 'receive_amount'])->lock(true)->find();
            if(empty($redenvelope)) {
                $walletModel->rollback();
                return errorResult('d');
            }
            
            $redenvelope = $redenvelope->toArray();
            $time = time();
            
            $updateData = ['receive_quantity' => $redenvelope['receive_quantity'] + 1, 'receive_amount' => $redenvelope['receive_amount'] + $amount];
            if($updateData['receive_quantity'] == $redenvelope['quantity']) {
                $updateData['status'] = 1;
            }
            
            $rs = $redenvelopeModel->modify(['id' => $redenvelope['id']], $updateData);
            if(!$rs) {
                $walletModel->rollback();
                return errorResult('e');
            }
            
            $rs = $receiveLogModel->add(['chat_id' => $chatId, 'chat_redenvelope_id' => $redenvelope['id'], 'user_id' => $sharer, 'hit_user_id' => $userId, 'amount' => $amount, 'add_time' => $time]);
            if(!$rs) {
                $walletModel->rollback();
                return errorResult('f');
            }
            
            $rs = model('RedenvelopeReceiveLog')->add(['chat_id' => $chatId, 'user_id' => $sharer, 'publisher' => $chat['user_id'], 'type' => 2, 'cover' => isset($chat['cover']) ? $chat['cover'] : '', 'content' => isset($chat['content']) ? substr($chat['content'], 0, 30) : '', 'amount' => $amount, 'add_time' => $time]);
            if(!$rs) {
                $walletModel->rollback();
                $redis->close();
                return errorResult('1g');
            }
            
            $rs = model('UserFinanceLog')->add(['user_id' => $userId, 'before_amount' => $wallet['amount'], 'amount' => $amount, 'type' => 2, 'related_id' => $chatId, 'add_time' => $time]);
            if(!$rs) {
                $walletModel->rollback();
                return errorResult('g');
            }
            
            $walletModel->commit();
            
            return successResult(['amount' => $amount]);
            
        } catch (\Exception $e) {
            $walletModel->rollback();
            return errorResult($e->getMessage());
        }
        
    }
    
    public function record() {
        $params = request()->get();
        $pk = isset($params['lastPk']) ? intval($params['lastPk']) : 0;
        $userId = isset($params['userId']) ? intval($params['userId']) : $this->userid;
        
        $where = [['user_id', '=', $userId], ['chat_type', 'in', [1, 2, 4, 5]]];
        if($pk > 0) {
            $where[] = ['chat_id', '<', $pk];
        }
        
        $chatList = model('Chat')
        ->where($where)
        ->field(['chat_id', 'content', 'cover', 'picture', 'chat_type', 'create_time'])
        ->order('chat_id desc')
        ->limit(20)
        ->select()
        ->toArray();
        
        if(!empty($chatList)) {
            $chatIds = [];
            foreach ($chatList as $chat) {
                if(in_array($chat['chat_type'], [2, 4, 5])) {
                    array_push($chatIds, $chat['chat_id']);
                }
            }

            if(!empty($chatIds)) {
                $goodsList = model('ChatGoods')->findAll(['chat_id' => $chatIds], ['goods_name', 'chat_id']);
                foreach ($chatList as &$chat) {
                    if(in_array($chat['chat_type'], [2, 4, 5])) {
                        foreach ($goodsList as $k => $goods) {
                            if($chat['chat_id'] == $goods['chat_id']) {
                                $chat['goods_name'] = $goods['goods_name'];
                                unset($goodsList[$k]);
                            }
                        }
                    }
                }
            }
            
        }
        
        return successResult(['list' => $chatList]);
    }
    
    public function copayInfo() {
        $chatId = request()->get('chatId', 0, 'intval');
        if($chatId <= 0) {
            return errorResult();
        }
        $chat = model('Chat')->findOne(['chat_id' => $chatId], ['user_id', 'content', 'picture']);
        if(empty($chat)) {
            return errorResult();
        }
        if($chat['user_id'] != $this->userid) { //别人的
            //判断是不是它的代理
            /* if(model('Agent')->isAgent($this->userid, $chat['user_id']) == false) {
                return errorResult('您无权限复制该商品');
            } */
        }
        
        $goods = model('ChatGoods')->findOne(['chat_id' => $chatId], ['goods_name', 'goods_no', 'sale_price', 'agent_price', 'bargain_price']);
        if(empty($goods)) {
            return errorResult();
        }
        
        unset($chat['user_id']);
        
        $chat['picture'] = json_decode($chat['picture'], true);
        
        return successResult(['chat' => array_merge($chat, $goods)]);
        
    }
    
    public function copyChat() {
        $formChatId = request()->get('chatId', 0, 'intval');
        if($formChatId <= 0) {
            return errorResult();
        }
        $chat = model('Chat')->findOne(['chat_id' => $formChatId], ['user_id', 'content', 'picture', 'location', 'latitude', 'chat_type']);
        if(empty($chat)) {
            return errorResult();
        }
        if($chat['user_id'] != $this->userid) { //别人的
            //判断是不是它的代理
            if(model('Agent')->isAgent($this->userid, $chat['user_id']) == false) {
                return errorResult('您无权限复制该商品');
            }
        }
        
        $goods = model('ChatGoods')->findOne(['chat_id' => $formChatId], ['goods_name', 'goods_no', 'sale_price', 'agent_price', 'bargain_price']);
        if(empty($goods)) {
            return errorResult();
        }
        
        $chat['picture'] = json_decode($chat['picture'], true);
        
        $data = [
            'chat_type' => 2,
            'user_id' => $this->userid,
            'create_time' => time(),
            'content' => $chat['content'],
            'cover' => $chat['picture'][0],
            'picture' => $chat['picture'],
            'location' => $chat['location'],
            'latitude' => $chat['latitude'],
        ];
        
        $chatId = model('Chat')->add($data);
        if(!$chatId) {
            return errorResult('复制失败1');
        }
        
        $_data = [
            'chat_id' => $chatId,
            'goods_name' => $goods['goods_name'],
            'goods_no' => $goods['goods_no'],
            'sale_price' => $goods['sale_price'],
            'agent_price' => $goods['agent_price'],
            //'form_chat_id' => $formChatId
        ];
        
        $result = model('ChatGoods')->add($_data);
        if(!$result){
            return errorResult('复制失败2');
        }
        
        Task::async(function() use ($data, $_data) {
            $data = array_merge($data, $_data);
            
            $redis = new Redis();
            $redis->setex('chat_' . $data['chat_id'], $data, 100 * 24 * 3600);
            
            try {
                $key = redisUserKey($data['user_id']);
                $user = $redis->get($key);
                if(!empty($user)) {
                    $user = json_decode($user, true);
                    $user['chat_number'] += 1;
                    $user['goods_number'] += 1;
                    $redis->set($key, $user);
                }
                
            } catch (\Exception $e) {
                
            }
            
            $redis->close();
        });
        
        return successResult();
    }
    
    public function delete() {
       $chatId = request()->post('chatId', 0, 'intval');
       if($chatId <= 0) {
           return errorResult();
       }

       $model = model('Chat');
       $chat = $model->findOne(['chat_id' => $chatId], ['user_id', 'chat_type']);
       if(empty($chat) || $chat['user_id'] != $this->userid) {
           return successResult();
       }
       
       $rs = $model->where(['chat_id' => $chatId])->delete();
       if(!$rs) {
           return errorResult();
       }
       
       model('ChatGoods')->where(['chat_id' => $chatId])->delete();
       
       if($chat['chat_type'] != 2) {
           switch ($chat['chat_type']) {
               case 4 : $model = model('GoodsRedenvelope'); break;
               case 5 : model('ChatBargain'); break;
               case 6 : model('ChatLuckDraw');
           }

           $model->where(['chat_id' => $chatId])->delete();
       }
       
       try {
           $redis = new Redis();
           $redis->del(redisChatKey($chatId));
           
           $key = redisUserKey($this->userid);
           $user = $redis->get($key);
           if(!empty($user)) {
               $user = json_decode($user, true);
               $user['chat_number'] -= 1;
               if($chat['chat_type'] == 2) {
                   $user['goods_number'] -= 1;
               }
               $redis->set($key, $user);
           }
           
           
           $redis->close();
       } catch (\Exception $e) {
       }
       
       return successResult();
    }

}











